package cn.com.pajx.pajx_visitor_v3.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.pajx.facelibrary.utils.DensityUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.adapter.VisiteProgressAdapter;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpFragment;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.bean.VisiteBean;
import cn.com.pajx.pajx_visitor_v3.bean.VisiteProgressBean;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.ui.view.TextureOutlineProvider;
import cn.com.pajx.pajx_visitor_v3.ui.view.dialog.CommonDialog;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.BaseImageUtils;
import cn.com.pajx.pajx_visitor_v3.utils.CornerTransform;
import cn.com.pajx.pajx_visitor_v3.utils.DateUtil;

/**
 * 预约信息显示的页面
 * create an instance of this fragment.
 */
@SuppressLint("NonConstantResourceId")
public class VisitorInfoFragment extends BaseMvpFragment<LoadDataPresenterImpl> {

    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_function)
    TextView tvFunction;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.tv_visitor)
    TextView tvVisitor;
    @BindView(R.id.tv_interviewee)
    TextView tvInterviewee;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_card_no)
    TextView tvCardNo;
    @BindView(R.id.tv_cause)
    TextView tvCause;
    @BindView(R.id.rv_progress)
    RecyclerView rvProgress;

    private VisiteProgressAdapter mAdapter;
    private final List<VisiteProgressBean> visiteProgressBeans = new ArrayList<>();
    private String visite_id, type;

    public VisitorInfoFragment() {
    }

    public static VisitorInfoFragment newInstance(String visite_id, String type) {
        VisitorInfoFragment fragment = new VisitorInfoFragment();
        Bundle args = new Bundle();
        args.putString(AppConstant.VISITE_ID, visite_id);
        args.putString(AppConstant.TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void beforeInitHead() {
        super.beforeInitHead();
        assert getArguments() != null;
        //拜访的id
        visite_id = getArguments().getString(AppConstant.VISITE_ID);
        type = getArguments().getString(AppConstant.TYPE);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_visitor_info;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected double loadWidthScale() {
        return 0.8;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //初始化RecyclerView
        initRecyclerView();
        //加载拜访的预约信息
        loadVisiteInfo();
    }

    /**
     * 加载拜访的预约信息
     */
    private void loadVisiteInfo() {
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("vis_id", visite_id);
        mPresenter.loadData(Api.VISITE_INFO, paramsMap, "VISITE_INFO", "努力加载中");
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        rvProgress.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false);
        rvProgress.setLayoutManager(linearLayoutManager);
        mAdapter = new VisiteProgressAdapter(mContext, R.layout.visite_progress_layout, visiteProgressBeans);
        rvProgress.setAdapter(mAdapter);
    }

    @OnClick({R.id.iv_close, R.id.tv_function})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close://关闭
                dismiss();
                break;
            case R.id.tv_function://结束拜访
                showEndView();
                break;
        }

    }

    private void showEndView() {
        new CommonDialog(mContext)
                .setTitle("结束拜访")
                .setMessage("确定要结束拜访吗？结束后请尽快离校！")
                .setChildClickListener(commonDialog -> {
                    finishVisite();
                    commonDialog.dismiss();
                })
                .show();
    }

    /**
     * 结束拜访
     */
    private void finishVisite() {
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("vis_id", visite_id);
        mPresenter.loadData(Api.VISITE_FINISH, paramsMap, "VISITE_FINISH", "");
    }

    @Override
    public void onSuccess(String data, String aesKey, String message, int code, String tag) {
        super.onSuccess(data, aesKey, message, code, tag);
        switch (tag) {
            case "VISITE_INFO"://拜访信息
                showVisiteInfo(data);
                break;
            case "LOAD_OSS_PHOTO"://oss照片路径
                showAvatar(data);
                break;
            case "VISITE_FINISH"://结束拜访
                EventBus.getDefault().post(new EventMessage(AppConstant.VISITE_END));
                dismiss();
                skip2Success("2");
                break;
        }
    }

    private void showAvatar(String data) {
        String photo_url = data.replaceAll("\"", "");
        //Glide设置圆角图片
        CornerTransform transform = new CornerTransform(mContext, DensityUtil.dp2px(mContext, 16));
        transform.setCornerRadius(false, false, false, false);
        if (TextUtils.isEmpty(photo_url)) {
            BaseImageUtils.setLocalCornerImage(mContext, ivPhoto, R.mipmap.icon_default, transform);
        } else {
            BaseImageUtils.setNetCornerImage(mContext, ivPhoto, photo_url, R.mipmap.icon_avatar_big, transform);
        }
    }

    private void showVisiteInfo(String data) {
        VisiteBean bean = new Gson().fromJson(data, VisiteBean.class);
        if (bean != null) {
            ivPhoto.setOutlineProvider(new TextureOutlineProvider(DensityUtil.dp2px(mContext, 16)));
            ivPhoto.setClipToOutline(true);
            tvVisitor.setText(TextUtils.isEmpty(bean.getVis_name_des()) ? bean.getVis_name() : bean.getVis_name_des());
            tvInterviewee.setText(TextUtils.isEmpty(bean.getUser_name_des()) ? bean.getUser_name() : bean.getUser_name_des());
            tvOrderTime.setText(DateUtil.getAllTime(bean.getTime_plan()));
            showStatusView(bean);
            tvPhone.setText(bean.getVis_phone_des());
            tvCardNo.setVisibility(TextUtils.isEmpty(bean.getVis_idcard_des()) ? View.INVISIBLE : View.VISIBLE);
            tvCardNo.setText(bean.getVis_idcard_des());
            tvCause.setText(bean.getVis_note());
            loadOSSPhoto(bean.getVis_photo());
        }
    }

    /**
     * 加载OSS上的图片URL
     *
     * @param vis_photo 图片的编号
     */
    private void loadOSSPhoto(String vis_photo) {
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("img_no", vis_photo);
        paramsMap.put("type", "1");
        mPresenter.loadData(Api.LOAD_OSS_PHOTO, paramsMap, "LOAD_OSS_PHOTO", "");
    }

    /**
     * 显示当前的拜访状态
     *
     * @param bean 数据
     */
    @SuppressLint("NotifyDataSetChanged")
    private void showStatusView(VisiteBean bean) {
        visiteProgressBeans.clear();
        String visite_status = bean.getVis_status();
        if (TextUtils.isEmpty(visite_status)) visite_status = "999";
        switch (visite_status) {
            case "0"://待审批
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                tvStatus.setText("待审批");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorOrange));
                tvStatus.setBackgroundResource(R.drawable.shape_status_approve);
                break;
            case "1"://待拜访
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                visiteProgressBeans.add(new VisiteProgressBean("审批通过时间：", bean.getTime_audit()));
                tvStatus.setText("待拜访");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorGreen));
                tvStatus.setBackgroundResource(R.drawable.shape_status_waiting);
                break;
            case "2"://拒绝拜访
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                visiteProgressBeans.add(new VisiteProgressBean("审批拒绝时间：", bean.getTime_audit()));
                tvStatus.setText("拒绝拜访");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorRed));
                tvStatus.setBackgroundResource(R.drawable.shape_status_reject);
                break;
            case "3"://拜访中
                tvFunction.setVisibility(TextUtils.isEmpty(type) ? View.INVISIBLE : View.VISIBLE);
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                visiteProgressBeans.add(new VisiteProgressBean("审批通过时间：", bean.getTime_audit()));
                visiteProgressBeans.add(new VisiteProgressBean("开始拜访时间：", bean.getTime_act()));
                tvStatus.setText("拜访中");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorBlue27));
                tvStatus.setBackgroundResource(R.drawable.shape_status_visiting);
                break;
            case "4"://结束拜访
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                visiteProgressBeans.add(new VisiteProgressBean("审批通过时间：", bean.getTime_audit()));
                visiteProgressBeans.add(new VisiteProgressBean("开始拜访时间：", bean.getTime_act()));
                visiteProgressBeans.add(new VisiteProgressBean("结束拜访时间：", bean.getTime_end()));
                tvStatus.setText("拜访结束");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorOrange22));
                tvStatus.setBackgroundResource(R.drawable.shape_status_finish);
                break;
            default://已失效
                visiteProgressBeans.add(new VisiteProgressBean("申请拜访时间：", bean.getCreate_time()));
                visiteProgressBeans.add(new VisiteProgressBean("申请已失效", ""));
                tvStatus.setText("已失效");
                tvStatus.setTextColor(mContext.getResources().getColor(R.color.colorGrey90));
                tvStatus.setBackgroundResource(R.drawable.shape_status_invalid);
                break;
        }
        //刷新拜访进度
        mAdapter.notifyDataSetChanged();
    }
}